package com.houxm.caipiao.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json的工具类
 * @author 学明
 *
 */
public class JsonUtils {
	private static JsonUtils jsonUtils;
	private static JsonFactory jsonFactory;
	private static ObjectMapper objectMapper;
	private JsonUtils() {}

	public static JsonUtils getInstance() {
		if (jsonUtils == null){
			synchronized (JsonUtils.class) {
				if (jsonUtils == null){
					jsonUtils = new JsonUtils();
				}
			}
		}
		return jsonUtils;

	}

	public static ObjectMapper getMapper() {
		if (objectMapper == null) {
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
			objectMapper = new ObjectMapper();
			objectMapper.setDateFormat(fmt);
			//objectMapper.setSerializationInclusion(Include.NON_NULL);
		}
		return objectMapper;
	}

	public static JsonFactory getFactory() {
		if (jsonFactory == null)
			jsonFactory = new JsonFactory();
		return jsonFactory;
	}

	public String obj2json(Object obj) {
		JsonGenerator jsonGenerator = null;
		try {
			jsonFactory = getFactory();
			objectMapper = getMapper();
			StringWriter out = new StringWriter();
			jsonGenerator = jsonFactory.createGenerator(out);
			objectMapper.writeValue(jsonGenerator, obj);
			return out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				if (jsonGenerator != null)
					jsonGenerator.close();
			} catch (Exception e2) {
			}
		}
		return null;
	}

	
	public <T>T json2obj(String json,TypeReference<T> typeReference)throws Exception{
		if(null==json){
			return null;
		}
		objectMapper = getMapper();
		return objectMapper.readValue(json, typeReference);
	}
	public Object json2objByException(String json, Class<?> clz) throws Exception{
		objectMapper = getMapper();
		return objectMapper.readValue(json, clz);
	}
	static BufferedWriter  bwnv = null;
	static BufferedWriter  bwnan = null;
	static BufferedWriter  bwnot = null;
	
	
	public static boolean write(BufferedReader br){
		
		return false;
	}
	
	public static void main(String[] args) throws Exception {
		
		String json = "[{\"aa\":\"aa1\",\"dd\":2},{\"aa\":\"aa2\",\"dd\":2},{\"aa\":\"aa3\",\"dd\":2},{\"aa\":\"aa4\",\"dd\":3}]";
		
		List<Map<String,Object>> r = JsonUtils.getInstance().json2obj(json, new TypeReference<List<Map<String,Object>>>(){});
		
		for(Map<String,Object> s:r){
			System.out.println(s.get("aa"));
		}
		
		System.out.println(JsonUtils.getInstance().obj2json(r));
		
	}
}